import 'package:path/path.dart';
import 'package:situation/domain/db/im_msg_content_domain.dart';
import 'package:situation/domain/db/system_config_domain.dart';
import 'package:situation/domain/db/user_latlon_domain.dart';
import 'package:sqflite/sqflite.dart';

class SqlProvider {
  Database? database;
  static const dbName = 'sxbdjw.db';

  // 单例
  factory SqlProvider() => _getInstance();

  static SqlProvider get instance => _getInstance();

  static SqlProvider? _instance;

  SqlProvider._internal() {
    // 初始化
    init();
  }

  init() async {
    await open();
  }

  static SqlProvider _getInstance() {
    _instance ??= SqlProvider._internal();
    return _instance!;
  }

  //初始化
  open() async {
    var databasePath = await getDatabasesPath();
    String path = join(databasePath, dbName);
    database = await openDatabase(path, version: 1,
        onCreate: (Database db, int version) async {
          // When creating the db, create the table

          // 初始化 systemConfig
          await db.execute(SystemConfigDomain.createTableSql);
          await db.execute(UserLatlonDomain.createTableSql);

          // await db.execute(ImMsgContentDomain.createTableSql);
          Batch batch = db.batch();
          SystemConfigDomain.initData.forEach((element) {
            batch.insert(SystemConfigDomain.tableName, element);
          });
          await batch.commit();


        });
  }

  //判断表是否存在
  isTableExits(String tableName) async {
    //内建表sqlite_master
    var sql =
        "SELECT * FROM sqlite_master WHERE TYPE = 'table' AND NAME = '$tableName'";
    List<Map<String, dynamic>>? res = await database?.rawQuery(sql);
    var returnRes = res != null && res.isNotEmpty;
    return returnRes;
  }

  /**
   * * description: query查询所有
   * * param1 tableName:表名
   * * param2 listColumns:列集合
   * * return {List<Map<String, dynamic>>}
   */
  query(String tableName) async {
    //var myColumns = ['name', 'type'];
    var result = await database?.query(tableName);
    return result;
  }

  queryOrder(String tableName,String orderBy) async {
    //var myColumns = ['name', 'type'];
    var result = await database?.query(tableName,orderBy: orderBy,);
    return result;
  }

  queryByWhereOrder(String tableName, String where,
      List<dynamic> whereArgs, order) async {
    //var myColumns = ['name', 'type'];
    var result = await database?.query(tableName,
        where: where, whereArgs: whereArgs,orderBy: order);
    return result;
  }
  /**
   * * description: query根据条件查询
   * * param1 tableName:表名
   * * param2 listColumns:列集合
   * * param3 where:条件，'Id = ?'
   * * param4 whereArgs:条件值，var myColumns = ['name', 'type'];
   * * return {List<Map<String, dynamic>>}
   */
  queryByWhere(String tableName, String where,
      List<dynamic> whereArgs) async {
    //var myColumns = ['name', 'type'];
    var result = await database?.query(tableName,
        where: where, whereArgs: whereArgs);
    return result;
  }

  /**
   * * description: 根据sql语句查询数据
   * * return {sql语句}
   */
  queryBysql(String sql) async {
    return await database?.rawQuery(sql);
  }

  /**
   * * description: insert
   * * param1 tableName:表名
   * * param2 values:列集合
   * * return {dynamic }
   */
  insert(String tableName, Map<String, dynamic> values) async {
    //var values = {'name':'my_name','type':'my_type'};
    print("插入的数据" + values.toString());
    await database?.insert(tableName, values);
  }

  insertAll(String tableName, List<Map<String, dynamic>> values) async {
    Batch batch = database!.batch();
    values.forEach((element) {
      batch.insert(tableName, element);
    });
    await batch.commit();

  }

  /**
   * * description: 更新
   * * param1 sql:语句，String update_sql = "UPDATE user SET username = ? WHERE id = ?";
   * * param2 arguments:列值，['paul','1']
   * * return {dynamic}
   */
  rawUpdate(String sql, List<dynamic> arguments) async {
    await database?.rawUpdate(sql, arguments);
  }

  /**
   * * description: delete
   * * param1 tableName:表名
   * * param2 where:条件，'Id = ?'
   * * param3 whereArgs:条件值，var myColumns = ['name', 'type'];
   * * return {dynamic}
   */
  delete(String tableName, String where, List<dynamic> whereArgs) async {
    //var myWhere = 'name = ?';
    //var myArgs = ['cat'];
    await database?.delete(tableName, where: where, whereArgs: whereArgs);
  }

  /**
   * * description: deleteAll
   * * param1 tableName:表名
   * * return {dynamic}
   */
  deleteAll(String tableName) async {
    await database?.delete(tableName);
  }

///关闭
// close() async {
//   database?.close();
//   database = null;
// }
}